﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BHair.Business.BaseData;
using BHair.Business;
using XLuSharpLibrary.CommonFunction;
using System.Data.SqlClient;
using System.Configuration;
using Size = System.Drawing.Size;
using System.Media;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows;
using System.Threading;  

namespace BHair.Base
{
    public partial class frmMember : Form
    {
        private string m_strMemberId = "";
        private bool m_bRun = false;
        string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
        /// <summary>新增会员信息。</summary>
        public frmMember()
        {
            InitializeComponent();
            this.Text = "新增会员信息";
        }
        //private FilterInfoCollection videoDevices;
        //private VideoCaptureDevice videoSource;
        /// <summary>编辑会员信息。</summary>
        /// <param name="memberid">会员编号(ID)</param>
        public frmMember(string memberid)
        {
            InitializeComponent();
            this.Text = "编辑会员信息";
            this.lblBalance.Text = "卡内余额：";
            this.numBalance.Enabled = false;
            this.numBalance.BackColor = Color.White;
            this.m_strMemberId = memberid;
        }

        #region 初化基础数据。

        /// <summary>初始化基础数据。</summary>
        private void LoadData()
        {
            this.cboStatus.SelectedIndex = 0;//状态
            this.LoadCard();//会员等级
            this.cboSex.SelectedIndex = 0;//性别
            this.LoadMonth();//生日
            this.dtpJoin.Value = DateTime.Now.Date;//加入日期
        }

        /// <summary>加载会员卡类型。</summary>
        private void LoadCard()
        {
            try
            {
                List<Card> lstCard = new Card().SelectList(0);
                this.cboLevel.DataSource = lstCard;
                this.cboLevel.ValueMember = "CardId";
                this.cboLevel.DisplayMember = "CardName";
                this.cboLevel.SelectedIndex = 0;
            }
            catch (Exception e2)
            {
                MessageBox.Show("请先添加卡类型" + e2.Message);
            }
        }

        #region 加载生日...

        /// <summary>加载月份</summary>
        private void LoadMonth()
        {
            this.cboMonth.Items.Clear();
            this.cboMonth.Items.Add("");
            for (int i = 1; i <= 12; i++)
            {
                this.cboMonth.Items.Add(i.ToString());
            }
            this.cboMonth.SelectedIndex = 0;
        }

        /// <summary>加载日</summary>
        /// <param name="m">月</param>
        private void LoadDay(int m)
        {
            this.cboDay.Items.Clear();
            int d = 31;
            if (m == 2)
            {
                d = 29;
            }
            else if (m == 4 || m == 6 || m == 9 || m == 11)
            {
                d = 30;
            }
            for (int i = 1; i <= d; i++)
            {
                this.cboDay.Items.Add(i.ToString());
            }
        }

        #endregion

        /// <summary>加载会员生日(日)</summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cboMonth.Text == "")
            {
                this.cboDay.Items.Clear();
                return;
            }
            this.LoadDay(int.Parse(this.cboMonth.Text));
            this.cboDay.SelectedIndex = 0;
        }

        /// <summary>加载初始金额</summary>
        private void cboLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.m_bRun)
            {
                Card objCard = new Card(int.Parse(this.cboLevel.SelectedValue.ToString()));
                this.numBalance.Value = objCard.Money;
            }
        }

        #endregion

        private void frmMember_Load(object sender, EventArgs e)
        {
            //xmxs();

            //videoSourcePlayer.Visible = false;
            //pictureBox1.Visible = true;   //隐藏pictureBox1
            // xm();
            jiazaijibie();
            this.LoadData();//初始化基础数据
            if (this.m_strMemberId != "")
            {
               
                this.LoadMember();//加载会员信息
               
            }
            this.m_bRun = true;

            //load();
            //dimage();
        }
        /// <summary>
        /// 加载会员级别
        /// </summary>
        public void jiazaijibie()
        {
            
            SqlConnection conn = new SqlConnection(constr);
            //DataTable dt = new DataTable("tab");
            conn.Open();
            string str = "SELECT [级别]  FROM [会员级别]";
          //  SqlCommand comm = new SqlCommand(str,conn);
            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter(str,conn);
           // DataRow row = dt.NewRow();
            //row["级别"] = "";
            //dt.Rows.Add(row);
            //sda.Fill(dt);
            //ds.Tables.Add(dt);
            // DataSet ds = new DataSet();

            sda.Fill(ds,"会员级别");
            comboBox1.DataSource = ds.Tables["会员级别"];
            comboBox1.DisplayMember = "级别";
            // comboBox1.Items.Add("请选择");
            conn.Close();
        }

        /// <summary>加载会员信息。</summary>
        private void LoadMember()
        {
            Member objMember = new Member(this.m_strMemberId);
            this.txtCard.Text = objMember.ID;
            this.txtName.Text = objMember.Name;
            this.cboStatus.SelectedIndex = objMember.Status;
            this.cboLevel.SelectedValue = objMember.CardID;
            this.numBalance.Value = objMember.Balance;
            this.txtPassword.Text = "";
            this.txtRemark.Text = objMember.Remark;
            this.cboSex.SelectedIndex = objMember.Sex;
            this.cboMonth.Text = objMember.Month.ToString();
            this.cboDay.Text = objMember.Day.ToString();
            this.txtPhone.Text = objMember.Phone;
            this.txtAddress.Text = objMember.Address;
            this.txtOther.Text = objMember.Other;
            this.dtpJoin.Value = objMember.JoinDate;
            this.numBalance.Value = objMember.Balance;
            this.txtIDCard.Text = objMember.IDCard;
            this.txtshengao.Text = objMember.Shengao;
            this.txttizhong.Text = objMember.Tizhong;
            this.txtxiongwei.Text = objMember.Xiongwei;
            this.txtyaowei.Text = objMember.Yaowei;
            this.txttunwei.Text = objMember.Tunwei;
            this.textBox1.Text = objMember.Biwei;
            this.textBox2.Text = objMember.Tuiwei;
            this.txtage.Text = objMember.Age.ToString();
            this.comboBox1.Text = objMember.会员级别.ToString();
            if (objMember.Ifyxq == 0)
            {
                checkBox1.Checked = false;
            }
            else if (objMember.Ifyxq == 1)
            {
                checkBox1.Checked = true;
            }
            try
            {
                byte[] imageData = objMember.Image;
                MemoryStream mStream = new MemoryStream();
                mStream.Write(imageData, 0, imageData.Length);
                pictureBox1.Image = new Bitmap(mStream);
                mStream.Close();
            }
            catch { }
           
            this.dateTimePicker1.Value = DateTime.Parse(objMember.Yxq.ToString());
        }

        /// <summary>保存会员信息</summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.txtCard.Text.Trim() == "")
            {
                MessageBox.Show("【会员卡号】不能为空，请输入！", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.txtCard.Focus();
                return;
            }

            Member objMember = new Member();
            objMember.ID = this.txtCard.Text;
            objMember.Name = this.txtName.Text.Trim();
            if (objMember.Name == "")
            {
                objMember.Name = "散客会员";
            }
            objMember.Status = this.cboStatus.SelectedIndex;
            objMember.CardID = int.Parse(this.cboLevel.SelectedValue.ToString());
            objMember.Password = (this.txtPassword.Text.Trim());
            objMember.Remark = this.txtRemark.Text.Trim();
            objMember.Sex = this.cboSex.SelectedIndex;
            objMember.Balance = this.numBalance.Value;
            objMember.会员级别 = this.comboBox1.Text;
            if (this.cboMonth.Text == "")
            {
                objMember.Month = 0;
            }
            else
            {
                objMember.Month = int.Parse(this.cboMonth.Text);
            }
            if (this.cboDay.Text == "")
            {
                objMember.Day = 0;
            }
            else
            {
                objMember.Day = int.Parse(this.cboDay.Text);
            }
            objMember.Phone = this.txtPhone.Text;
            objMember.Address = this.txtAddress.Text.Trim();
            objMember.Other = this.txtOther.Text.Trim();
            objMember.JoinDate = this.dtpJoin.Value;
            objMember.IDCard = this.txtIDCard.Text.Trim();
            string strTempId = objMember.ExistsMemberCard(objMember.ID);
            objMember.Shengao = this.txtshengao.Text;
            objMember.Tizhong = this.txttizhong.Text;
            objMember.Xiongwei = this.txtxiongwei.Text;
            objMember.Yaowei = this.txtyaowei.Text;
            objMember.Tunwei = this.txttunwei.Text;
            objMember.Biwei = this.textBox1.Text;
            objMember.Tuiwei = this.textBox2.Text;
            objMember.Age =Int32.Parse( this.txtage.Text);
            if (pictureBox1.Image != null)
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        Bitmap bmp = new Bitmap(pictureBox1.Image);
                        bmp.Save(ms, pictureBox1.Image.RawFormat);
                        byte[] image = ms.ToArray();
                        objMember.Image = image;
                    }
                }
                catch { }
            }
            else
            {
                objMember.Image = null;
            }
            if (checkBox1.Checked == true)
            {
                objMember.Ifyxq = 1;
            }
            else if (checkBox1.Checked == false)
            {
                objMember.Ifyxq = 0;
            }
            objMember.Yxq = dateTimePicker1.Text;
            if (this.m_strMemberId != "")
            {
                objMember.ID = this.m_strMemberId;
                if (strTempId != "" && strTempId != this.m_strMemberId)
                {
                    MessageBox.Show("已经存在相同会员卡号，请输重新输入！", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.txtCard.Focus();
                    return;
                }

                objMember.UpdateMember();
            }
            else
            {
                if (strTempId != "")
                {
                    MessageBox.Show("已经存在相同会员卡号，请输重新输入！", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.txtCard.Focus();
                    return;
                }
               
                skje();
                chuanzhi.bkcardid = txtCard.Text;
                chuanzhi.bankaname = txtName.Text;
                frmsk sk = new frmsk();
                sk.ShowDialog();
                if (chuanzhi.result == 1)
                {
                    objMember.InsertMember();
                    uphuiyuanjibie();
                    frmjccz cz = new frmjccz();
                    cz.ShowDialog();
                    SqlConnection conn33 = new SqlConnection(constr);
                    conn33.Open();
                    string sql33 = string.Format("UPDATE 制卡 SET fl=0 where card='{0}'", txtCard.Text);
                    SqlCommand comm33 = new SqlCommand(sql33, conn33);
                    comm33.ExecuteNonQuery();
                }
                else
                {

                }
            }

            baocun();
            DialogResult = DialogResult.OK;
            this.Close();
        }
        //修改会员级别
        public void uphuiyuanjibie()
        {
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string str =string.Format( "update member set 会员级别='{0}',积分='0.00' where mid='{1}' ",comboBox1.Text,txtCard.Text);
            SqlCommand comm = new SqlCommand(str,conn);
            comm.ExecuteNonQuery();
            conn.Close();
        }
        public void skje()
        {
            //根据会员分类查询应收办卡金额
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string sql =string.Format( "SELECT cmoney FROM card where cname='{0}'",cboLevel.Text);
            SqlCommand comm = new SqlCommand(sql,conn);
            SqlDataReader sdr = comm.ExecuteReader();
            while (sdr.Read())
            {
                chuanzhi.fkje =Convert.ToDecimal( sdr["cmoney"].ToString());
            }
            conn.Close();
        }
        /// <summary>取消</summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
                string sql2 = "DELETE FROM [BHairDB].[dbo].[csmxfalse]";
                SqlConnection conn2 = new SqlConnection(constr);
                conn2.Open();
                SqlCommand comm2 = new SqlCommand(sql2, conn2);
                comm2.ExecuteNonQuery();
                conn2.Close();
            }
            catch (Exception ex1)
            {
                MessageBox.Show(ex1.Message);
            }
            this.Close();
        }

        private void txtCard_KeyPress(object sender, KeyPressEventArgs e)
        {
            NumericClass.NumberAccpter(sender, e, false);
        }

        private void txtIDCard_KeyPress(object sender, KeyPressEventArgs e)
        {
            NumericClass.NumberAccpter(sender, e, false);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            frmPrintBar frmPrintBar = new frmPrintBar(txtCard.Text);
            frmPrintBar.ShowDialog();
        }
        /*
        public void xm()
        {
            string sqlxm = "SELECT [id],[spname],[jcdj]FROM [BHairDB].[dbo].[jc]";
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            try
            {
                conn.Open();
                SqlDataAdapter sda = new SqlDataAdapter(sqlxm, conn);
                DataSet ds = new DataSet();
                sda.Fill(ds, "jc");
                skinComboBox1.DataSource = ds.Tables["jc"];
                skinComboBox1.DisplayMember = "spname";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        */
        private void button1_Click(object sender, EventArgs e)
        {


            //string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            //xmcsadd();

        }
        /*
        //实现为卡 添加 项目次数
        
        public void xmcsadd() 
        {
            /*int index = this.skinDataGridView1.Rows.Add();

            this.skinDataGridView1.Rows[index].Cells[0].Value = this.skinComboBox1.Text;
            this.skinDataGridView1.Rows[index].Cells[1].Value = this.txtci.Text;
             
            //判断如果项目没有重复之后执行
            int rows = this.skinDataGridView1.Rows.Count;//获取总行数
            //总列数
            int fanhui=0;
            if (rows > 0)
            {
                for (int i = 0; i < rows; i++)
                {
                    
                    
                        if (this.skinComboBox1.Text == this.skinDataGridView1.Rows[i].Cells[0].Value.ToString())
                        {
                            fanhui = 1;
                           // MessageBox.Show("chongfu");
                            break;
                        }
             
                }
                if (fanhui > 0)
                {
                    MessageBox.Show("此卡以有此项目，请重新选择");
                }
                else 
                {
                    int index = this.skinDataGridView1.Rows.Add();
                    this.skinDataGridView1.Rows[index].Cells[0].Value = this.skinComboBox1.Text;
                    this.skinDataGridView1.Rows[index].Cells[1].Value = this.txtci.Text;
                    //将计次项目次数插入到临时表 csmxfalse中
                    int cs = Int32.Parse(this.txtci.Text.ToString());
                    string cardid = this.txtCard.Text.ToString();
                    string jcsp = this.skinComboBox1.Text;
                    string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
                    SqlConnection conn9 = new SqlConnection(constr);
                    string sqlstr = string.Format("SELECT [id] FROM [BHairDB].[dbo].[jc] where spname='{0}'", jcsp);
                    SqlCommand comm9 = new SqlCommand(sqlstr, conn9);
                    conn9.Open();
                    SqlDataReader sdr = comm9.ExecuteReader();
                    int spid;
                    while (sdr.Read())
                    {
                        spid = Int32.Parse(sdr["id"].ToString().Trim());
                        string sqlcr = string.Format("INSERT INTO [BHairDB].[dbo].[csmxfalse]"
                        + "           ([cardID]"
                        + "           ,[jcspid]"
                        + "           ,[jcnum])"
                        + "     VALUES"
                        + "           ('{0}'"
                        + "           ,{1}"
                        + "           ,{2})", cardid, spid, cs);
                        SqlConnection conn1 = new SqlConnection(constr);
                        try
                        {
                            conn1.Open();
                            SqlCommand comm1 = new SqlCommand(sqlcr, conn1);
                            comm1.ExecuteNonQuery();
                            conn1.Close();
                            xmxs();
                        }
                        catch (Exception eq)
                        {
                            conn1.Close();
                            MessageBox.Show(eq.Message);
                        }
                    }
                    conn9.Close();
                }
            }
            else 
            {
                int index = this.skinDataGridView1.Rows.Add();
                this.skinDataGridView1.Rows[index].Cells[0].Value = this.skinComboBox1.Text;
                this.skinDataGridView1.Rows[index].Cells[1].Value = this.txtci.Text;
                //将计次项目次数插入到临时表 csmxfalse中
                int cs = Int32.Parse(this.txtci.Text.ToString());
                string cardid = this.txtCard.Text.ToString();
                string jcsp = this.skinComboBox1.Text;
                string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
                SqlConnection conn9 = new SqlConnection(constr);
                string sqlstr = string.Format("SELECT [id] FROM [BHairDB].[dbo].[jc] where spname='{0}'", jcsp);
                SqlCommand comm9 = new SqlCommand(sqlstr, conn9);
                conn9.Open();
                SqlDataReader sdr = comm9.ExecuteReader();
                int spid;
                while (sdr.Read())
                {
                    spid = Int32.Parse(sdr["id"].ToString().Trim());
                    string sqlcr = string.Format("INSERT INTO [BHairDB].[dbo].[csmxfalse]"
                    + "           ([cardID]"
                    + "           ,[jcspid]"
                    + "           ,[jcnum])"
                    + "     VALUES"
                    + "           ('{0}'"
                    + "           ,{1}"
                    + "           ,{2})", cardid, spid, cs);
                    SqlConnection conn1 = new SqlConnection(constr);
                    try
                    {
                        conn1.Open();
                        SqlCommand comm1 = new SqlCommand(sqlcr, conn1);
                        comm1.ExecuteNonQuery();
                        conn1.Close();
                        xmxs();
                    }
                    catch (Exception eq)
                    {
                        conn1.Close();
                        MessageBox.Show(eq.Message);
                    }
                }
                conn9.Close();
            }
            
               
    }
    
        }
        */
        /*
        public void xmxs() 
        {
            string sql3 =string.Format( "select spname,jcnum from csmx inner join jc on csmx.jcspid=jc.id where cardID='{0}'",this.txtCard.Text.ToString());
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn2 = new SqlConnection(constr);
            try 
            {
                conn2.Open();
                SqlDataAdapter sda1 = new SqlDataAdapter(sql3,conn2);
                DataTable dt2 = new DataTable();
                sda1.Fill(dt2);

                foreach(DataRow row in dt2.Rows)
                {
                    int index = skinDataGridView1.Rows.Add();
                    skinDataGridView1.Rows[index].Cells["Column1"].Value = row["spname"];
                    skinDataGridView1.Rows[index].Cells["Column2"].Value = row["jcnum"];
                }
                //this.skinDataGridView1.DataSource = dt2;
                //SqlCommand comm2 = new SqlCommand(sql3, conn2);
                //comm2.ExecuteNonQuery();
                conn2.Close();
                
            }catch(Exception ew)
            {
                conn2.Close();
                MessageBox.Show(ew.Message);
            }
        }
        */

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //xmxs();
        }
        /*
         * 计次项目保存
         * 1 把项目次数的临时表中的数据 保存到正式表csmx中
         * 2 清空临时表csmxfalse
         * */
        public void baocun() 
        {

            //查询项目次数临时表中的数据,并且插入数据到csmx表里
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            SqlConnection conn1 = new SqlConnection(constr);
            SqlConnection conn2 = new SqlConnection(constr);
            string cardid = "";
            int xmid = 0;
            int csnum = 0;

            try
            {
                conn.Open();
                string sql =string.Format( "SELECT [id],[cardID],[jcspID],[jcnum]FROM [BHairDB].[dbo].[csmxfalse] where cardID='{0}'",this.txtCard.Text);
                SqlCommand comm = new SqlCommand(sql,conn);
                SqlDataReader sdr = comm.ExecuteReader();
                while (sdr.Read()) 
                {
                    cardid = sdr["cardID"].ToString().Trim();
                    xmid =Int32.Parse( sdr["jcspID"].ToString().Trim());
                    csnum = Int32.Parse(sdr["jcnum"].ToString().Trim());
                    string sql1 =string.Format( "INSERT INTO [BHairDB].[dbo].[csmx]([cardID],[jcspid],[jcnum])VALUES('{0}',{1},{2})",cardid,xmid,csnum);
                    conn1.Open();
                    SqlCommand comm1 = new SqlCommand(sql1,conn1);
                    comm1.ExecuteNonQuery();
                    conn1.Close();
                }
                //清空临时表
                string sql2 = "DELETE FROM [BHairDB].[dbo].[csmxfalse]";
                
                conn2.Open();
                SqlCommand comm2 = new SqlCommand(sql2,conn2);
                comm2.ExecuteNonQuery();
                conn2.Close();
            }
            catch (Exception ex1) 
            {
                conn.Close();
                conn1.Close();
                conn2.Close();   
                MessageBox.Show(ex1.Message);
            }
        }
        #region 保存路径
        #region 加载摄像头
        /*
        public void load() 
        {
            try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                foreach (FilterInfo device in videoDevices)
                {
                    tscbxCameras.Items.Add(device.Name);
                }

                tscbxCameras.SelectedIndex = 0;

            }
            catch (ApplicationException)
            {
                tscbxCameras.Items.Add("No local capture devices");
                videoDevices = null;
            }
            
        }
        */
        #endregion
        private string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }
        #endregion
        #region 启用拍照
        private void button2_Click(object sender, EventArgs e)
        {
            
            //CameraConn();
           
        }

        #endregion
        /*
        #region 连接摄像头
        private void CameraConn()
        {
            try
            {
                this.pictureBox1.Visible = false;
                this.videoSourcePlayer.Visible = true;
                VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
                videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
                videoSource.DesiredFrameRate = 1;

                videoSourcePlayer.VideoSource = videoSource;
                videoSourcePlayer.Start();
            }
            catch
            {
                MessageBox.Show("摄像机异常");
            }
        }
        
        #endregion
    */
        #region 拍照并且显示在图片上
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer.IsRunning)
                {
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),
                                IntPtr.Zero,
                                 Int32Rect.Empty,
                                BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName =string.Format( GetImagePath() + "\\" + "{0}" + ".jpg",this.txtCard.Text);
                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }
                    
                    //拍照完成后关摄像头并刷新同时关窗体
                    if (videoSourcePlayer != null && videoSourcePlayer.IsRunning)
                    {
                        videoSourcePlayer.SignalToStop();
                        videoSourcePlayer.WaitForStop();
                    }

                    
                    bcimage();
                    pictureBox1.Visible = true; //显示pictureBox1
                    videoSourcePlayer.Visible = false; //隐藏 videoSourcePlayer
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常：" + ex.Message);
            }
        }
        #region 获取图片路径
        public void bcimage() 
        {
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string filePath = string.Format(AppDomain.CurrentDomain.BaseDirectory + @"PersonImg\{0}.jpg", txtCard.Text);//路径
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] imageBytes = new byte[fs.Length];
            BinaryReader br = new BinaryReader(fs);
            imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//图片转换成二进制流
           // string strSql = "UPDATE [BHairDB].[dbo].[member] SET [image] ='{0}' WHERE member.mid='{1}'";
            SqlCommand comm = new SqlCommand("UPDATE [BHairDB].[dbo].[member] SET [image] =@image WHERE member.mid=@kahao", conn);
            comm.Parameters.Add("image", SqlDbType.Image);
            comm.Parameters.Add("kahao", SqlDbType.NVarChar);
            comm.Parameters["image"].Value = imageBytes;
            comm.Parameters["kahao"].Value = txtCard.Text;
            int count = 0;
            count=comm.ExecuteNonQuery();
            if (count > 0)
            {
                dimage();
            }
            else 
            {
                MessageBox.Show("no");
            }
            //string strSql = string.Format("insert into [SBS].[dbo].[Model] ([M_QRCode],[M_Skills] ) values (@imag,'2')");
        }
        #endregion
        #endregion
       
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.ShowDialog();
                string lj = this.openFileDialog1.FileName.ToString();
                this.pictureBox1.Image = Image.FromFile(lj);
                pictureBox1.Visible = true;
            }
            catch (Exception ee) { MessageBox.Show("请选择图片"); }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.pictureBox1.Visible = false;
            //dimage();
        }
        #region 读取图片
        public void dimage() 
        {
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string sql =string.Format( "SELECT [image] FROM [BHairDB].[dbo].[member] where member.mid='{0}'",txtCard.Text);
            SqlCommand comm = new SqlCommand(sql,conn);
            SqlDataReader sdr = comm.ExecuteReader();
            byte[] imagebytes=null;
             
            while (sdr.Read()) 
            {
                string sd = sdr["image"].ToString();
                if (sd != null)
                {
                    imagebytes = (byte[])sdr["image"];
                }
                else
                {
                    pictureBox1.Image = null;
                }
            }
            
                MemoryStream ms = new MemoryStream(imagebytes);
                Bitmap bmpt = new Bitmap(ms);
                pictureBox1.Visible = true;
                pictureBox1.Image = bmpt;
          


        }
        #endregion
        public void ifnull() 
        {
            string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            int flid = 0;
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string sql = string.Format("SELECT cid, cname FROM card where cname='{0}'", cboLevel.Text);
            SqlCommand comm = new SqlCommand(sql, conn);
            SqlDataReader sdr = comm.ExecuteReader();
            while (sdr.Read())
            {
                flid = Int32.Parse(sdr["cid"].ToString());
            }
            chuanzhi.cardfl = flid;
            frmxzkh xz = new frmxzkh();
            xz.ShowDialog();
            txtCard.Text = chuanzhi.xzkh;
        }
    }
}
